import {createSlider} from './dom'
import ControlledDom from './ControlledDom'
import {isELementNode, createError, throttle} from './util'
import {noop} from './util'

class Slider{
    constructor(container, options = {}){
        if (!isELementNode(container)) throw createError(Slider, 'param need element')

        if (options.value && options.value < 0 && options.value>100){
            throw createError(Slider, 'options.value is postive number and it smaller than 100')
        }

        this.node = createSlider()
        this.container = container
        this.onSlide = options.onSlide || noop
        this.value = options.value || 50
        
    }

    init(){
        this.btn = this.node.getElementsByClassName('emm-slider-btn')[0]
        this.line = this.node.getElementsByClassName('emm-slider-line')[0]
        this.container.appendChild(this.node)

        let Threshold = 10,
        maxDis = this.line.clientWidth - Threshold,
        onSlide = throttle(this.onSlide, 50),
        x = ~~(this.value / 100 * maxDis)

        this.moveBtn = new ControlledDom(this.btn, {
            listenerDom: this.node,
            direction: 'horizontal',
            positionX: x,
            onMove(x){
                if (x <  Threshold || x > maxDis) return false
                onSlide(~~(x / maxDis * 100))
                return true
            }
        })
        this.moveBtn.init()
    }

}


export default Slider
